<template>
  <div class="frank_map_right">
    <div class="box_top">
      <el-card :body-style="{ padding: '20px' }" shadow="never">
        <template #header>
          <div class="card-header">
            <span>当日救治情况</span>
            <el-button type="primary" plain @click="handleShowList">{{
              isShowList ? '隐藏列表' : '显示列表'
            }}</el-button>
            <el-switch
              v-model="switchValue"
              inline-prompt
              active-text="提示音开启"
              inactive-text="提示音关闭"
              style="font-size: 8px; --el-switch-off-color: #909090"
              @change="handleSwitchChange"
            />
            <div class="fk_audio" v-if="isAudioShow">
              <audio
                id="myAudio"
                ref="musicRef"
                controls
                :src="audioUrl"
              ></audio>
            </div>
          </div>
        </template>
        <div class="card_body">
          <div class="item_function">
            <img src="~assets/imgHome/rightImg/acceptPatient.png" alt="" />
            <div>
              <div class="send_hospital_value" @click="handleAcceptPatient">
                {{ curNum }}
              </div>
              <div class="send_hospital_text">接诊伤病员</div>
            </div>
          </div>
          <div class="item_function">
            <img src="~assets/imgHome/rightImg/sendHosp.png" alt="" />
            <div>
              <div class="send_hospital_value" @click="handleSendHospital">
                {{ curNum_sendHospital }}
              </div>
              <div class="send_hospital_text">送往医院伤病员</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <transition name="el-fade-in-linear">
      <div class="box_bottom" v-show="isShowList">
        <el-scrollbar>
          <el-card class="box_card" shadow="never">
            <template #header>
              <div class="card_header">
                <span>状态跟踪</span>
              </div>
            </template>
            <el-table
              :data="patientRecordStateList"
              style="width: 100%"
              max-height="300"
              height="300"
            >
              <el-table-column
                prop="Name"
                label="姓名"
                width="70"
                show-overflow-tooltip
              />
              <el-table-column label="状态" width="100" fixed="right">
                <template #default="scope">
                  <span
                    v-if="scope.row.State == '现场处置'"
                    :style="{ color: '#8172d5' }"
                    >{{ scope.row.State }}</span
                  >
                  <span
                    v-else-if="scope.row.State == '送院途中'"
                    :style="{ color: '#00bc7a' }"
                    >{{ scope.row.State }}</span
                  >
                  <span
                    v-else="scope.row.State == '已入院'"
                    :style="{ color: '#1890ff' }"
                    >{{ scope.row.State }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                prop="UpdateTime"
                label="更新时间"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="HospitalName"
                label="送往地点"
                show-overflow-tooltip
              ></el-table-column>
            </el-table>
          </el-card>
          <!-- <el-card class="box_card" shadow="never">
            <template #header>
              <div class="card_header">
                <span>智能调度</span>
                <div class="btn_smart">
                  <el-button
                    type="primary"
                    plain
                    @click="handleRegulationMeasure"
                    >调度方案</el-button
                  >
                  <el-button type="primary" plain @click="handleEmergencyPlan"
                    >传染病统计信息表</el-button
                  >
                  <el-button type="primary" plain @click="handleClearLine"
                    >线路清除</el-button
                  >
                </div>
              </div>
            </template>
            <el-table
              ref="znddTableRef"
              :data="PatientRecord_XCQXWXZList"
              style="width: 100%"
              max-height="200"
              height="180"
              highlight-current-row
              current-row-key="id"
              @row-click="curRowClick"
              stripe
            >
              <el-table-column
                prop="Name"
                label="姓名"
                width="100"
                show-overflow-tooltip
              />
              <el-table-column
                prop="VenuesName"
                label="场馆名称"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="AmbName"
                label="车辆"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="HospitalName"
                label="医院"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="PatientRecordCode"
                label="病例号"
                width="100"
                show-overflow-tooltip
              />
              <el-table-column
                prop="Symptom"
                label="病情"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="IllnessLevel"
                label="病情等级"
                width="100"
                show-overflow-tooltip
              />
              <el-table-column
                prop="Telephone"
                label="联系电话"
                width="120"
                show-overflow-tooltip
              />

              <el-table-column label="操作" width="60" fixed="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    @click="handleShowLine(scope.$index, scope.row)"
                    round
                    >路线</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card> -->
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="病人列表" name="first">
              <div class="patient_table">
                <el-table
                  :data="patientRecordList"
                  style="width: 100%"
                  max-height="300"
                  height="300"
                  :stripe="true"
                >
                  <el-table-column
                    prop="Name"
                    label="姓名"
                    width="100"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="PatientRecordCode"
                    label="病例号"
                    width="100"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="SeeADoctorDate"
                    label="就诊时间"
                    width="180"
                  />
                  <el-table-column
                    prop="IsGroup"
                    label="是否群组事件"
                    width="120"
                    show-overflow-tooltip
                  >
                    <template #default="scope">
                      <div>
                        <span v-if="scope.row.IsGroup == true">{{ '是' }}</span>
                        <span v-else-if="scope.row.IsGroup == false">{{
                          '否'
                        }}</span>
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="状态" width="100" fixed="right">
                    <template #default="scope">
                      <div>
                        <span
                          v-if="scope.row.State == '现场处置'"
                          :style="{ color: '#8172d5' }"
                          >{{ scope.row.State }}</span
                        >
                        <span
                          v-else-if="scope.row.State == '送院途中'"
                          :style="{ color: '#00bc7a' }"
                          >{{ scope.row.State }}</span
                        >
                        <span
                          v-else="scope.row.State == '已入院'"
                          :style="{ color: '#1890ff' }"
                          >{{ scope.row.State }}</span
                        >
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" width="60" fixed="right">
                    <template #default="scope">
                      <el-button
                        size="small"
                        @click="handlePatientRecordMsg(scope.$index, scope.row)"
                        round
                        >病历</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-scrollbar>
      </div>
    </transition>
    <!-- 弹窗 -->
    <div>
      <!-- 应急预案 -->
      <emergency-plan :flag="emergencyPlanFlag"></emergency-plan>
    </div>
  </div>
</template>

<script>
import {
  reactive,
  toRefs,
  onBeforeMount,
  onMounted,
  ref,
  watch,
  onUnmounted,
  onBeforeUnmount,
} from 'vue';
import VueEvent from 'utils/event.js';
// 网络请求
import { GetCureNum, GetCureNum_SendHospital } from 'network/getBaseInfoNum';
import {
  GetPatientRecordState,
  GetPatientRecord_XCQXWXZ,
  GetPatientRecordList,
} from 'network/patientRecord';

import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';
import { patientBaseList } from 'modelUtils/returnModel';
// import SendHospital from './compChildMessage/SendHospital.vue'
import AcceptPatient from './compChildMessage/AcceptPatient.vue';
import { setupMapState } from '../../../store/utils/hook';
import { useRouter } from 'vue-router';
// 弹窗组件
import EmergencyPlan from '../../dialog/EmergencyPlan.vue';

export default {
  name: 'MapRight',
  components: {
    // SendHospital,
    AcceptPatient,
    EmergencyPlan,
  },
  props: [],
  setup(props, ctx) {
    const znddTableRef = ref();
    const musicRef = ref();
    const store = useStore();
    const router = useRouter();
    const state = reactive({
      drawer: ref(false),
      isShowList: ref(false),
      isShowRegulationMeasure: ref(false),
      isShowEmergencyPlan: ref(false),
      code: ref('001'),
      activeName: ref('first'),
      acceptPatient: ref(0), //接诊伤病员
      sendHospPatient: ref(1), //送往医院伤病员
      curRow: ref(null),
      curRowVenueId: ref(''),
      inteligentSchedulData: ref([]),
      //右侧栏数据
      curNum: ref(0),
      curNum_sendHospital: ref(0),
      // 状态跟踪
      patientRecordStateList: ref([]),
      PatientRecord_XCQXWXZList: ref([]),
      patientRecordList: ref([]),
      timer: ref(null),

      // 弹窗
      emergencyPlanFlag: 1,
      isAudioShow: false,
      audioUrl: '',
      switchValue: false,
    });
    const { ACVCodesVx } = setupMapState('app', ['ACVCodesVx']);
    const { userInfoVx } = setupMapState('app', ['userInfoVx']);
    const { curTaskRowVx } = setupMapState('HospVenuAmbuModule', [
      'curTaskRowVx',
    ]);
    const handleShowList = () => {
      state.isShowList = !state.isShowList;
    };
    const handlePlayAudio = () => {
      if (musicRef.value) musicRef.value.play();
    };
    const handleSwitchChange = (val) => {
      if (val) {
        state.audioUrl = require('../../../assets/music/deskVoice.mp3');
        state.isAudioShow = true;
      } else {
        state.audioUrl = '';
        state.isAudioShow = false;
      }
    };
    // 调度方案
    const handleRegulationMeasure = () => {
      // console.log("调度方案", state.curRow);
      // 先判断是否选择了一行
      if (state.curRow) {
        if (state.curRow.AmbName.indexOf('指挥部派车') != -1) {
          VueEvent.emit('showRegulationMeasure', {
            row: state.curRow,
            isShowRegulationMeasure: true,
          });
        } else {
          ElMessage({ message: '无需调度！', type: 'warning' });
        }
      } else {
        ElMessage({ message: '请选择一行任务开始调度！', type: 'warning' });
      }
    };
    // 应急预案
    const handleEmergencyPlan = () => {
      // 打开弹窗
      state.emergencyPlanFlag++;
    };
    /**
     * 智能调度
     */
    // 显示线路按钮
    const handleShowLine = (index, row) => {
      // console.log(row);
      if (
        row.ambLat != null &&
        row.ambLng != null &&
        row.hosLat != null &&
        row.hosLng != null &&
        row.ambLat > 2 &&
        row.ambLng > 2 &&
        row.hosLat > 2 &&
        row.hosLng > 2
      ) {
        ctx.emit('getLinePosition', row);
      } else {
        ElMessage({ message: '暂无去往医院线路', type: 'warning' });
      }
    };
    // 清理线路按钮
    const handleClearLine = () => {
      ctx.emit('clearLine', true);
    };
    // 选择当前行
    const curRowClick = (row, column, e) => {
      // console.log(row);
      state.curRowVenueId = row.VenuesCode;
      state.curRow = row;
      // 保存智能调度点击的一条任务到vuex
      store.dispatch('HospVenuAmbuModule/saveClickTaskRow', { row });
    };
    // 高亮方法
    const handleCurrentChange = (row) => {
      znddTableRef.value.setCurrentRow(row);
    };
    /**
     * 病人病例
     */
    // 病例按钮
    const handlePatientRecordMsg = (index, row) => {
      // console.log(index, row);
      VueEvent.emit('showDialogEvent', { row: row, isShowDialog: true });
    };
    /** 监听是否有病人 有则显示列表，没有则不显示列表 */
    watch(
      () => state.curNum,
      () => {
        if (state.curNum > 0) {
          state.isShowList = true;
        } else {
          state.isShowList = false;
        }
      },
    );

    /**
     * 接诊和送往医院患者
     */
    const handleAcceptPatient = () => {
      // ctx.emit("acceptPatientEmit")
      localStorage.setItem('path', '/users');
      router.push('/users');
    };
    const handleSendHospital = () => {
      // console.log("送往医院")
      localStorage.setItem('path', '/users');
      router.push('/users');
      // ctx.emit("sendHospitalEmit")
    };

    onBeforeMount(() => {});
    onMounted(async () => {
      try {
        // let tmout = setTimeout(async () => {
        //   if (localStorage.getItem('userInfo') != null) {
        //     // 判断是否选择了全部的场馆  -1代表的是全部场馆
        //     if (ACVCodesVx.value.venueCode == -1) {
        //       ACVCodesVx.value.venueCode = userInfoVx.value.venueCode;
        //     }
        //     // 请求右侧栏伤病员数量curNumcurNum_sendHospital
        //     let curNum = await GetCureNum({
        //       cityCode: ACVCodesVx.value.cityCode,
        //       venueCode: ACVCodesVx.value.venueCode,
        //     });
        //     state.curNum = curNum.rows;
        //     let curNum_sendHospital = await GetCureNum_SendHospital({
        //       cityCode: ACVCodesVx.value.cityCode,
        //       venueCode: ACVCodesVx.value.venueCode,
        //     });
        //     state.curNum_sendHospital = curNum_sendHospital.rows;

        //     // 状态跟踪
        //     let patientRecordStateList = await GetPatientRecordState({
        //       cityCode: ACVCodesVx.value.cityCode,
        //       venueCode: ACVCodesVx.value.venueCode,
        //     });
        //     if (patientRecordStateList != null) {
        //       state.patientRecordStateList = patientRecordStateList;
        //     }
        //     // console.log(state.patientRecordStateList);
        //     // 智能调度（现场去向为选择XCQXWXZ）
        //     let patientRecord_XCQXWXZList = await GetPatientRecord_XCQXWXZ({
        //       cityCode: ACVCodesVx.value.cityCode,
        //       venueCode: ACVCodesVx.value.venueCode,
        //     });
        //     if (patientRecord_XCQXWXZList != null) {
        //       // console.log("12345", patientRecord_XCQXWXZList)
        //       let ai = patientRecord_XCQXWXZList.find(
        //         (item) => item.AmbName.indexOf('指挥部') > -1,
        //       );
        //       if (ai != null) {
        //         handlePlayAudio();
        //       }
        //       state.PatientRecord_XCQXWXZList = patientBaseList(
        //         patientRecord_XCQXWXZList,
        //       );
        //     } else {
        //       musicRef.value.pause();
        //     }
        //     // 表格重新高亮
        //     // console.log(curTaskRowVx.value)
        //     if (curTaskRowVx.value != undefined) {
        //       let findHigthRow = state.PatientRecord_XCQXWXZList.find(
        //         (item) => {
        //           return (
        //             item.PatientRecordCode ==
        //             curTaskRowVx.value.PatientRecordCode
        //           );
        //         },
        //       );
        //       handleCurrentChange(findHigthRow);
        //     }
        //     // console.log(state.PatientRecord_XCQXWXZList);

        //     // 病例列表
        //     let patientRecordList = await GetPatientRecordList(
        //       ACVCodesVx.value,
        //     );
        //     if (patientRecordList != null) {
        //       state.patientRecordList = patientRecordList;
        //     }
        //     // console.log(state.patientRecordList);
        //     clearTimeout(tmout);
        //   } else {
        //     clearTimeout(tmout);
        //   }
        // }, 2000);
        state.timer = setInterval(async () => {
          if (localStorage.getItem('userInfo') != null) {
            // 判断是否选择了全部的场馆  -1代表的是全部场馆
            if (ACVCodesVx.value.venueCode == -1) {
              ACVCodesVx.value.venueCode = userInfoVx.value.venueCode;
            }
            // 请求右侧栏伤病员数量curNumcurNum_sendHospital
            let curNum = await GetCureNum({
              cityCode: ACVCodesVx.value.cityCode,
              venueCode: ACVCodesVx.value.venueCode,
            });
            state.curNum = curNum.rows;
            let curNum_sendHospital = await GetCureNum_SendHospital({
              cityCode: ACVCodesVx.value.cityCode,
              venueCode: ACVCodesVx.value.venueCode,
            });
            state.curNum_sendHospital = curNum_sendHospital.rows;

            // 状态跟踪
            let patientRecordStateList = await GetPatientRecordState({
              cityCode: ACVCodesVx.value.cityCode,
              venueCode: ACVCodesVx.value.venueCode,
            });
            if (patientRecordStateList != null) {
              state.patientRecordStateList = patientRecordStateList;
            }
            // console.log(state.patientRecordStateList);
            // 智能调度（现场去向为选择XCQXWXZ）
            let patientRecord_XCQXWXZList = await GetPatientRecord_XCQXWXZ({
              cityCode: ACVCodesVx.value.cityCode,
              venueCode: ACVCodesVx.value.venueCode,
            });
            if (patientRecord_XCQXWXZList != null) {
              // console.log("12345", patientRecord_XCQXWXZList)
              let ai = patientRecord_XCQXWXZList.find(
                (item) => item.AmbName.indexOf('指挥部') > -1,
              );
              if (ai != null) {
                handlePlayAudio();
              }
              state.PatientRecord_XCQXWXZList = patientBaseList(
                patientRecord_XCQXWXZList,
              );
            } else {
              musicRef.value.pause();
            }
            // 表格重新高亮
            // console.log(curTaskRowVx.value)
            if (curTaskRowVx.value != undefined) {
              let findHigthRow = state.PatientRecord_XCQXWXZList.find(
                (item) => {
                  return (
                    item.PatientRecordCode ==
                    curTaskRowVx.value.PatientRecordCode
                  );
                },
              );
              handleCurrentChange(findHigthRow);
            }
            // console.log(state.PatientRecord_XCQXWXZList);

            // 病例列表
            let patientRecordList = await GetPatientRecordList(
              ACVCodesVx.value,
            );
            if (patientRecordList != null) {
              state.patientRecordList = patientRecordList;
            }
            // console.log(state.patientRecordList);
          } else {
            clearInterval(state.timer);
          }
        }, 5000);
      } catch (error) {
        throw error;
      }
    });
    onBeforeUnmount(() => {});
    onUnmounted(() => {
      clearInterval(state.timer);
    });
    const refState = toRefs(state);
    return {
      ...refState,
      znddTableRef,
      musicRef,
      // 事件
      handleShowList,
      handleSwitchChange,
      handleRegulationMeasure,
      handleEmergencyPlan,
      handleShowLine,
      handlePatientRecordMsg,
      curRowClick,
      handleClearLine,
      handleAcceptPatient,
      handleSendHospital,
    };
  },
};
</script>
<style scoped>
:deep(.box_top .el-card__header .el-button) {
  margin-right: 10px;
  float: right;
  position: fixed;
  right: 5px;
  border-radius: 5px;
  top: 70px;
  height: 27px;
}

:deep(.box_top .el-card__header .el-button span) {
  font-size: 13px;
}

.box_top .card_body .item_function {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: #f2f5f8;
  height: 70px;
  width: 220px;
}

.box_top .card_body .item_function img {
  height: 50px;
  width: 50px;
}

.box_top .card_body {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 70px;
}

.box_top .card_body .send_hospital_value,
.box_top .card_body .send_hospital_text {
  text-align: center;
}

.box_top .card_body .send_hospital_value {
  font-size: 22px;
  font-weight: 700;
  cursor: pointer;
}

.box_top .card_body .send_hospital_value:hover {
  color: #619af3;
}

.frank_map_right .box_card,
.frank_map_right .demo-tabs {
  margin-top: 5px;
}

:deep(.el-card__header) {
  height: 37px;
  line-height: 37px;
  padding: 0;
}

:deep(.el-card__header span) {
  margin-left: 10px;
  font-weight: 600;
}

.frank_map_right .card_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__body) {
  padding: 5px;
}

:deep(.el-table th.el-table__cell) {
  background: #f5f6f7;
}

:deep(.el-tabs__header) {
  background: #fff;
  margin: 0px;
}

.btn_smart .el-button {
  margin-right: 10px;
  width: auto;
  height: 27px;
}

:deep(.btn_smart .el-button span) {
  font-size: 13px;
}

:deep(.el-tabs--top .el-tabs__item.is-top:last-child) {
  font-size: 16px;
  margin-left: 5px;
  font-weight: 700;
}

.notification {
  position: fixed;
  bottom: 5px;
  right: 5px;
}

@media screen and (max-height: 950px) {
  .frank_map_right .box_bottom {
    height: 700px;
  }
}

@media screen and (max-height: 876px) {
  .frank_map_right .box_bottom {
    height: 630px;
  }
}

@media screen and (max-height: 790px) {
  .frank_map_right .box_bottom {
    height: 430px;
  }
}

.fk_audio {
  position: absolute;
  display: none;
}
</style>
